package license

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

// LicensePage 处理License页面的HTTP请求
func LicensePage(c *gin.Context) {
	html := `
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>生成 License</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
        }
        .card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            padding: 24px;
            margin-bottom: 24px;
        }
        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 16px;
            border-bottom: 1px solid #e8e8e8;
        }
        .card-title {
            font-size: 20px;
            font-weight: 600;
            margin: 0;
        }
        .btn {
            background: #1890ff;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        .btn:hover {
            background: #40a9ff;
        }
        .btn-primary {
            background: #1890ff;
        }
        .btn-success {
            background: #52c41a;
        }
        .btn-download {
            background: #722ed1;
        }
        .form-group {
            margin-bottom: 16px;
        }
        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
        }
        .required::after {
            content: " *";
            color: red;
        }
        .form-input {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            font-size: 14px;
            box-sizing: border-box;
        }
        .form-input:focus {
            outline: none;
            border-color: #40a9ff;
            box-shadow: 0 0 0 2px rgba(24,144,255,0.2);
        }
        .checkbox {
            display: flex;
            align-items: center;
        }
        .checkbox input {
            margin-right: 8px;
        }
        .form-actions {
            text-align: center;
            margin-top: 24px;
        }
        .btn-space {
            margin: 0 10px;
        }
        .verification-result {
            padding: 20px;
            text-align: center;
            border-radius: 4px;
            margin-top: 20px;
        }
        .valid {
            background-color: #f6ffed;
            border: 1px solid #b7eb8f;
            color: #52c41a;
        }
        .invalid {
            background-color: #fff2f0;
            border: 1px solid #ffccc7;
            color: #ff4d4f;
        }
        .info {
            background-color: #e6f7ff;
            border: 1px solid #91d5ff;
            color: #1890ff;
        }
        h3 {
            margin-top: 0;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>生成 License</h1>
            <p>获取硬件信息并生成License</p>
        </div>
        
        <div class="card">
            <div class="card-header">
                <h2 class="card-title">生成License</h2>
                <button class="btn btn-primary" onclick="getHardwareInfo()">获取硬件信息</button>
            </div>
            <form id="licenseForm">
                <div class="form-group">
                    <label class="form-label required">CPU ID</label>
                    <input type="text" id="cpuId" class="form-input" placeholder="请输入CPU ID" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label required">CPU Name</label>
                    <input type="text" id="cpuName" class="form-input" placeholder="请输入CPU Name" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label required">MAC地址</label>
                    <input type="text" id="macAddress" class="form-input" placeholder="请输入MAC地址" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label">公网IP</label>
                    <input type="text" id="publicIp" class="form-input" placeholder="请输入公网IP">
                </div>
                
                <div class="form-group">
                    <label class="form-label required">过期日期</label>
                    <input type="date" id="expiryDate" class="form-input" required>
                </div>
                
                <div class="form-group checkbox">
                    <input type="checkbox" id="admin">
                    <label>是否管理员</label>
                </div>
                
                <div class="form-actions">
                    <button type="button" class="btn btn-download btn-space" onclick="downloadHardwareInfo()">
                        下载硬件信息
                    </button>
                    <button type="button" class="btn btn-primary btn-space" onclick="generateLicense()">
                        生成License
                    </button>
                    <button type="button" class="btn btn-space" onclick="resetForm()">
                        重置
                    </button>
                </div>
            </form>
        </div>
        
        <div class="card">
            <div class="card-header">
                <h2 class="card-title">验证License</h2>
                <button class="btn btn-success" onclick="verifyLicense()">
                    验证License
                </button>
            </div>
            <div id="verificationResult">
                <div class="verification-result info">
                    <p>点击"验证License"按钮检查当前License状态</p>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 获取硬件信息
        function getHardwareInfo() {
            fetch('/api/license/generate')
                .then(response => response.json())
                .then(data => {
                    if (data.status === 200) {
                        document.getElementById('cpuId').value = data.data.cpuId;
                        document.getElementById('cpuName').value = data.data.cpuName;
                        document.getElementById('macAddress').value = data.data.macAddress;
                    } else {
                        alert(data.message || '获取硬件信息失败');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('获取硬件信息失败，请稍后重试');
                });
        }

        // 下载硬件信息
        function downloadHardwareInfo() {
            const cpuId = document.getElementById('cpuId').value;
            const cpuName = document.getElementById('cpuName').value;
            const macAddress = document.getElementById('macAddress').value;
            const expiryDate = document.getElementById('expiryDate').value;
            const isAdmin = document.getElementById('admin').checked;
            
            // 检查必填项
            if (!cpuId || !cpuName || !macAddress || !expiryDate) {
                alert('请填写所有必填项');
                return;
            }
            
            // 构造要下载的数据
            const hardwareInfo = {
                cpuId: cpuId,
                cpuName: cpuName,
                macAddress: macAddress,
                expiryDate: expiryDate,
                admin: isAdmin
            };
            
            // 创建下载链接
            const blob = new Blob([JSON.stringify(hardwareInfo, null, 2)], {type: 'application/json'});
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'hardware_info.json';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }

        // 生成License
        function generateLicense() {
            const formData = {
                cpuId: document.getElementById('cpuId').value,
                cpuName: document.getElementById('cpuName').value,
                macAddress: document.getElementById('macAddress').value,
                publicIp: document.getElementById('publicIp').value,
                expiryDate: document.getElementById('expiryDate').value,
                admin: document.getElementById('admin').checked
            };

            // 检查必填项
            if (!formData.cpuId || !formData.cpuName || !formData.macAddress || !formData.expiryDate) {
                alert('请填写所有必填项');
                return;
            }

            fetch('/api/license/generate', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(formData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 200) {
                    // 创建下载链接
                    const blob = new Blob([JSON.stringify(data.data, null, 2)], {type: 'application/json'});
                    const url = URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = 'license.json';
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    URL.revokeObjectURL(url);
                    alert('License生成成功');
                } else {
                    alert(data.message || 'License生成失败');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('生成License失败，请稍后重试');
            });
        }

        // 验证License
        function verifyLicense() {
            fetch('/api/license/status')
                .then(response => response.json())
                .then(data => {
                    const resultDiv = document.getElementById('verificationResult');
                    if (data.status === 200) {
                        resultDiv.innerHTML = 
                            '<div class="verification-result valid">' +
                            '<h3>✓ License 有效</h3>' +
                            '<p>' + data.message + '</p>' +
                            '</div>';
                    } else {
                        resultDiv.innerHTML = 
                            '<div class="verification-result invalid">' +
                            '<h3>✗ License 无效</h3>' +
                            '<p>' + data.message + '</p>' +
                            '</div>';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('验证License失败，请稍后重试');
                });
        }

        // 重置表单
        function resetForm() {
            document.getElementById('licenseForm').reset();
        }

        // 设置默认过期日期为明天
        window.onload = function() {
            const today = new Date();
            const tomorrow = new Date(today);
            tomorrow.setDate(tomorrow.getDate() + 1);
            const formattedDate = tomorrow.toISOString().split('T')[0];
            document.getElementById('expiryDate').min = formattedDate;
        }
    </script>
</body>
</html>
`
	c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(html))
}